import re
import time
import sqlite3

'''
Iterate through all loaded modules and send the message to each of them.
This is not ideal but works for now. Future versions will use compiled
regexps and/or TRIGGER to only call modules as needed

Also, sends messages to databaes via log_message()
'''

def message(self, sender, channel, flags, message, modules, DB, DEBUG, NICK):

    if message.startswith('join '):
        message = message.replace('join ', '')
        channel_join = message.split()[0]
        try:
            self.command_call('join %s' %(channel_join))
             if DEBUG == True:
                print 'joined channel %s' %(channel_join)
        except:
            print 'couldn\'t join channel %s' %(channel_join)

    #save messages for future use, use with caution or disable entirely
    def log_message(sender, message, channel):
        if (DEBUG):
            print sender.nickname
            print message
            print time.ctime()
        con=sqlite3.connect(DB)
        write_message = con.execute("INSERT INTO messages (nickname, message, time, channel) VALUES (?, ?, ?, ?)", (sender.nickname, message, time.time(), str(channel)))
        con.commit()
        con.close()

    log_message(sender, message, channel)
    
    #strip out the bot's name from any message
    if message.startswith(NICK + ':'):
        message = message.replace(NICK + ':', '')

    #send message to each loaded module, calling it's required main() method
    for module in modules:
        # each module currently must have a "main" method, not ideal?
        method = getattr(module, 'main')
        method(self, sender, channel, flags, message, DB, DEBUG)
